<template>
  <a-modal :width="900" :title="title" :after-close="reset" @ok="submit">
    <a-form ref="formRef" :model="form" :rules="rules" :label-col="{ style: { width: '80px' } }">
      <a-row :gutter="24">
        <a-col :span="24">
          <a-form-item label="规格名称：" name="ruleName">
            <a-input v-model:value="form.ruleName" :maxlength="20" placeholder="请输入标题名称" />
          </a-form-item>
        </a-col>
        <a-col v-for="(item, index) in form.ruleValue" :key="index" :span="24" class="noForm">
          <a-form-item>
            <div class="attr-box">
              <span class="mr5">{{ item.value }}</span>
              <CloseCircleOutlined @click="handleRemove(index)" />
            </div>
            <div class="flex middle">
              <a-tag v-for="(j, indexn) in item.detail" :key="indexn" closable size="medium" :disable-transitions="false"
                class="mb5 mr10" @close="handleClose(item.detail, indexn)">
                {{ j }}
              </a-tag>
              <a-input v-if="item.inputVisible" ref="saveTagInput" v-model:value="item.attrsVal" class="tagInput"
                size="small" @blur="createAttr(item.attrsVal, index)" />
              <a-button v-else class="button-new-tag" size="small" @click="showInput(item)">+ 添加</a-button>
            </div>
          </a-form-item>
        </a-col>
      </a-row>
      <a-row v-if="isBtn" :gutter="24" justify="start" align="top">
        <a-col :span="7">
          <a-form-item label="规格：">
            <a-input v-model:value="attrsName" placeholder="请输入规格" />
          </a-form-item>
        </a-col>
        <a-col :span="7">
          <a-form-item label="规格值：">
            <a-input v-model:value="attrsVal" placeholder="请输入规格值" />
          </a-form-item>
        </a-col>
        <a-col :span="3">
          <a-button type="primary" class="mr10" @click="createAttrName">确定</a-button>
        </a-col>
        <a-col :span="3">
          <a-button @click="offAttrName">取消</a-button>
        </a-col>
      </a-row>
      <a-button v-if="!isBtn" type="primary" class="ml40 mt10" @click="addBtn">添加新规格</a-button>
    </a-form>
  </a-modal>
</template>

<script setup lang="ts">
import { storeproductattrAddup, storeproductattrinfo } from './api';
import { storeproductattr, type Istoreproductattr } from './entity';
import { validReg } from '@/utils/validate';

const props = withDefaults(defineProps<{
  data: Partial<Istoreproductattr>
}>(), {
})
let isBtn = $ref(false)
let attrsName = $ref('')
let attrsVal = $ref('')
const title = computed(() => props.data.id ? '编辑' : '新增')
const { formRef, submit, close } = useDialog({ validCallback: save })

let form = $ref(new storeproductattr())
watchEffect(() => {
  if (props.data.id) {
    storeproductattrinfo(props.data.id).then(res => {
      let { ruleValue, ...temp } = res
      form.setProps(temp)
      form.ruleValue = JSON.parse(ruleValue)
    })
  }
})

const rules = {
  storeproductattrName: [validReg('required', '请输入用户名')]
}

onMounted(() => {
})
// 添加按钮
function addBtn() {
  isBtn = true
}
function handleClose(item: any, index: number) {
  item.splice(index, 1)
}
// 取消
function offAttrName() {
  isBtn = false
}
// 删除
function handleRemove(index: number) {
  form?.ruleValue.splice(index, 1)
}
function showInput(item: any) {
  item.inputVisible = true
}
// 添加属性
function createAttr(num: string, idx: number) {
  if (num) {
    form.ruleValue[idx].detail.push(num)
    form.ruleValue[idx].attrsVal = ''
    form.ruleValue[idx].inputVisible = false
  } else {
    AntMessage.warning('请添加属性');
  }
}
// 添加规则名称
function createAttrName() {
  if (attrsName && attrsVal) {
    const data = {
      value: attrsName,
      detail: [
        attrsVal
      ],
      attrsVal: '',
      inputVisible: false
    }
    form.ruleValue.push(data)
    attrsName = '';
    attrsVal = '';
    isBtn = false;
  } else {
    AntMessage.warning('请添加规格名称');
  }
}
const emit = defineEmits(['change'])
function save() {
  if (form.ruleValue.length === 0) {
    return AntMessage.warning('请至少添加一条属性规格！');
  }
  storeproductattrAddup({ ...form, ruleValue: JSON.stringify(form.ruleValue) }).then(() => {
    AntMessage.success('保存成功')
    close()
    emit('change')
  })
}

function reset() {
  form = new storeproductattr()
}
</script>

<style lang="scss">
.tagInput {
  width: 80px;
}

.button-new-tag {
  height: 28px;
  line-height: 26px;
  padding-top: 0;
  padding-bottom: 0;
}

.input-new-tag {
  width: 90px;
  margin-left: 10px;
  vertical-align: bottom;
}

.footer {
  justify-content: flex-end;
}

.attr-box {
  display: inline-block;
  border: 1px solid #aaa;
  padding: 2px 8px;
  margin-bottom: 10px;
  border-radius: 20px;
}
</style>